package com.woniu.woniuproject.web;

import com.woniu.woniuproject.config.SendSms;
import com.woniu.woniuproject.entity.Account;
import com.woniu.woniuproject.entity.User;
import com.woniu.woniuproject.mapper.InfoMapper;
import com.woniu.woniuproject.service.AccountService;
import com.woniu.woniuproject.service.LooseLabelService;
import com.woniu.woniuproject.utils.ResponseResult;
import com.woniu.woniuproject.vo.AddLooseLabelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 功能描述:<br>
 * 〈〉
 *
 * @author 徐威
 * @create 2020/11/19
 * @since 1.0.0
 */
@Controller
@Slf4j
@RequestMapping("LooseLabelWEB")
public class Loose_LabelControllerWeb {
    @Autowired
    LooseLabelService looseLabelService;
    @Autowired
    SendSms sendSms;
    @Autowired
    InfoMapper infoMapper;
    @ResponseBody
    @RequestMapping("/code")
    public ResponseResult<String> LooseLabelCode(@RequestParam("phone")String phone, HttpServletRequest req){
        if (phone==null&&"".equals(phone)){
            return new ResponseResult<>(500,"手机号不能为空");
        }
        if (phone.length()!=11){
            try {
                long l = Long.parseLong(phone);
            }catch (Exception e){
            log.debug("phone:{}"+phone +"手机号格式异常");
            }finally {
                return new ResponseResult<>(500,"手机号格式错误请查询输入");
            }
        }
        int code =500;
        String msg="系统超时";
        String debtInfoCode = (String) req.getSession().getAttribute("DebtInfoCode");
        if (debtInfoCode!=null){
            req.getSession().removeAttribute("DebtInfoCode");
        }
        //生成验证码
        String codes= UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",codes);
        //使用验证码
      Map isSend=sendSms.send(phone,"SMS_205464231",param);
        //设置过期时间
        if ((Boolean) isSend.get("boolean")){
            req.getSession().setAttribute("DebtInfoCode",codes);
            req.getSession().setMaxInactiveInterval(5*60);
            if (((String) isSend.get("message").toString().substring(12,14)).equals("OK")){
               code=200;
               msg="发送成功";
            }else {
               msg="找不到该手机号";
            }
        }
        return new ResponseResult<>(code,msg);
    }
    //@Value("${flie.location}")
    String fliePath="D:/nginx-1.14.0/html/";
    @RequestMapping("/add")
    public String addLooseLabel(Map map, AddLooseLabelVo addLooseLabelVo,HttpServletRequest request) throws IOException {

        String code = (String) request.getSession().getAttribute("DebtInfoCode");
        User user = (User) request.getSession().getAttribute("loginUser");
        if (addLooseLabelVo.getDebtormoney()<0){
            log.debug("借款金额不能小于是负数==================================");
            map.put("results","借款金额，不能小于0，请重新申请");
            return "borrow.html";
        }
     /*
        if (user==null){
            log.debug("未登录==================================");
            map.put("results","请先登录");
            return "borrow.html";
        }
        if (!"1".equals(user.getRealnamestatus())){
            log.debug("未实名认证==================================");
            map.put("results","请先实名认证");
            return "borrow.html";
        }
        if (addLooseLabelVo.getDebtorname()!=null&&!addLooseLabelVo.getDebtorname().equals(user.getRealname())){
            log.debug("借款人姓名与本人不一致==================================");
            map.put("results","您输入的借款人姓名有误请重新输入");
            return "borrow.html";
        }
        addLooseLabelVo.setDeborid(user.getId());

        addLooseLabelVo.setDebtorname(user.getRealname());*/
     //登录删除
        addLooseLabelVo.setDeborid(user.getId());

   /*     if (!addLooseLabelVo.getCode().equals(code)){
            log.debug("验证码错误===============================");
            map.put("results","验证码错误");
            return "borrow.html";
        }*/

        if ( addLooseLabelVo.getDebtortypedesc()==null&&addLooseLabelVo.getDebtortypedesc().isEmpty()&&"".equals(addLooseLabelVo.getDebtortypedesc().getOriginalFilename())){
            log.debug("上传文件为空==================================");
            map.put("results","请选择上传文件");
            return "borrow.html";
        }
        String Filename =  addLooseLabelVo.getDebtortypedesc().getOriginalFilename();
        if (!Filename.endsWith(".docx")){
            log.debug("上传文件格式错位==================================" +Filename);
            map.put("results","只能上传.docx格式文件，请重新选择");
            return "borrow.html";
        }
        String uuid= UUID.randomUUID().toString().replace("-","");
        String name = uuid+Filename.substring(Filename.lastIndexOf("."));
        addLooseLabelVo.setFliename(name);
        addLooseLabelVo.setDebordate(new Date());
        addLooseLabelVo.getDebtortypedesc().transferTo(new File(fliePath+name));

       int rew = looseLabelService.addLooseLabel(addLooseLabelVo);
       if (rew>0){
           int id=looseLabelService.queryByLastId();
           infoMapper.insert(id,name);
           map.put("results","申请成功，正在审核");
           return "borrow.html";
       }
        map.put("results","申请超时，请刷新重试");
       return "borrow.html";
    }
    @Autowired
    AccountService accountService;
    @RequestMapping("/transaction")
    @ResponseBody
    public ResponseResult<String> transaction(HttpServletRequest request,int labelid,Double money,String payPassword){
        User user = (User) request.getSession().getAttribute("loginUser");
       /* if (!user.getPaypassword().equals(payPassword)){
            return  new ResponseResult<>(500,"支付密码错误");
        }*/
        if (user.getRealnamestatus()=="0"){
            return  new ResponseResult<>(500,"尚未实名认证，购买失败");
        }
        Account account =  accountService.queryByUserId(user.getId());
        if (account.getBalance()<money){
            return  new ResponseResult<>(500,"余额不足，请先充值");
        }
        int row =  looseLabelService.transaction(user,labelid,money,account);
        if (row>0){
            return  new ResponseResult<>(200,"购买成功，筹款结束后开始计息");
        }
        return  new ResponseResult<>(500,"系统超时");
    }

    @RequestMapping("/queryOne/{id}")
    public String queryOneBykey(Map map,@PathVariable int id){
        Map<String,Object> map1 = looseLabelService.queryOneBykey(id);
        map.put("looseLabel",map1.get("looseLabel"));
        return "chanpin.html";
    }
}
